<script lang="ts" setup>
import { h, reactive, ref, onMounted } from 'vue'
import { NTransfer, NTree, NCard, NButton, NSpace } from 'naive-ui'
import type { TransferOption } from 'naive-ui'
import { useOrgStore } from '@/stores/orgStore'

const orgStore = useOrgStore()

const props = defineProps(["value"])
const emits = defineEmits(["cancel", "update:value"])

const selectedOrg = ref<string[]>([])
const options = reactive<TransferOption[]>([])

onMounted(() => {
    selectedOrg.value.length = 0
    for (let i = 0; i < props.value.length; i++) {
        selectedOrg.value.push(props.value[i])
    }
    options.length = 0
    for (let i = 0; i < orgStore.orgInfoList.length; i++) {
        options.push({
            label: orgStore.orgInfoList[i].orgName,
            value: orgStore.orgInfoList[i].orgCode
        })
    }

})

function renderSourceList(props: { onCheck: (checkedValueList: Array<string | number>) => void, checkedOptions: TransferOption[], pattern: string }) {
    return h(
        NTree,
        {
            keyField: 'value',
            checkable: true,
            selectable: false,
            blockLine: true,
            checkOnClick: true,
            data: orgStore.orgInfoTree,
            pattern: props.pattern,
            checkedKeys: selectedOrg.value,
            onUpdateCheckedKeys: (checkedKeys: Array<string | number>) => {
                props.onCheck(checkedKeys)
            }
        }
    )
}

function submit() {
    emits("update:value", selectedOrg.value)
    emits("cancel")
}

</script>
<template>
    <n-card title="部门选择" style="width:550px;height:450px;" :header-style="{ padding: '12px 24px' }" closable
        @close="emits('cancel')">
        <n-transfer v-model:value="selectedOrg" :options="options" source-title="待选部门" target-title="已选部门"
            :render-source-list="renderSourceList" />
        <template #footer>
            <n-space justify="end">
                <n-button @click="emits('cancel')">取消</n-button>
                <n-button @click="submit" type="primary">确定</n-button>
            </n-space>
        </template>
    </n-card>
</template>
<style scoped></style>